import { UserRole } from '@app/db/models/user.model';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { ROLES_KEY } from './role.decorator';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log('role guard');

    // 允许哪些角色可以通过验证
    // 这些参数从 '@Roles()' 装饰器中获取
    const allowableRoles = this.reflector.getAllAndOverride<UserRole[]>(
      ROLES_KEY,
      [context.getHandler(), context.getClass()],
    );

    // 获取 token 中的 user数据
    // 前提是路由需要配置为需要 token 验证
    const { user } = context.switchToHttp().getRequest();

    if (allowableRoles && user) {
      return allowableRoles.some((role) => user.role === role);
    } else {
      return true;
    }
  }
}
